﻿using System;
using System.Collections.Generic;
using MediaSage.Lib.Database;

namespace MediaSage.Lib.Utilities
{
    /// <summary>
    /// Handles image updates, gives us the ability to have an instanced way to wait for all updates to be done
    /// </summary>
    public class ImageUpdateManager
    {
        /// <summary>
        /// The image updates currently in progress
        /// </summary>
        private List<Guid> imageUpdates;

        private Configuration.Config config;
        private Logger logger;

        public ImageUpdateManager(Configuration.Config Config)
        {
            this.config = Config;
            this.imageUpdates = new List<Guid>();
            this.logger = config.Logger;
            logger.Log("ImageUpdateManager.ImageUpdateManager() Initialized");
        }

        /// <summary>
        /// Enques an update thread
        /// </summary>
        /// <param name="imageEntity">Image Entity to update</param>
        public void GetUpdate(ImageEntity imageEntity)
        {
            logger.Log("Entering ImageUpdateManager.GetUpdate(ImageEntity)");
            Guid item = config.ThreadManager.CreateImageUpdateThread(imageEntity);
            imageUpdates.Add(item);
            logger.Log("Exiting ImageUpdateManager.GetUpdate(ImageEntity)");
        }

        /// <summary>
        /// Waits for all update threads in the list to be complete
        /// </summary>
        public void WaitForUpdates()
        {
            logger.Log("Entering ImageUpdateManager.WaitForUpdates()");
            if (imageUpdates.Count > 0)
            {
                config.ThreadManager.WaitForResults(imageUpdates);
            }
            logger.Log("Updates Complete()");
            logger.Log("Exiting ImageUpdateManager.WaitForUpdates()");
        }

        /// <summary>
        /// Waits for the updates to be complete before disposing
        /// </summary>
        ~ImageUpdateManager()
        {
            if (imageUpdates.Count > 0)
            {
                config.ThreadManager.WaitForResults(imageUpdates);
            }
        }
    }
}